package com.br.android.widing;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.br.android.widing.db.WidingCategoriaCursor;
import com.br.android.widing.db.WidingCategoriaDAO;
import com.br.android.widing.db.WidingDAO;
import com.br.android.widing.entity.Gasto;

public class EditGastoActivity extends SherlockActivity {

	private EditText editTextNomeGasto;
	private EditText editTextValorGasto;
	private Spinner spinnerMoedaCorrente;
	private Spinner spinnerCategoria;

	private int idGasto;

	private DecimalFormat formatAux = new DecimalFormat("###,###,##0.00");
	private SimpleDateFormat formatData = new SimpleDateFormat(
			"dd/MM/yyyy HH:mm");

	private WidingDAO dao;

	private WidingCategoriaDAO categoriaDAO;
	private WidingCategoriaCursor categoriaCursor;

	// adapter para o spinner
	private ArrayAdapter<String> adapter;
	private List<String> listCategorias;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_edit_gasto);
		dao = new WidingDAO(this);
		categoriaDAO = new WidingCategoriaDAO(this);

		editTextNomeGasto = (EditText) findViewById(R.id.editTextGasto);
		editTextValorGasto = (EditText) findViewById(R.id.editTextValor);
		spinnerCategoria = (Spinner) findViewById(R.id.spinnerCategoria);
		if (categoriaDAO.consultarCategorias().getCount() > 0) {
			spinnerCategoria.setPrompt("Selecione uma categoria");
		} else {
			spinnerCategoria
					.setPrompt("N\u00e3o existem categorias cadastradas");
		}

		Intent intent = getIntent();
		idGasto = intent.getExtras().getInt("id");
		editTextNomeGasto.setText(intent.getExtras().getString("nomegasto"));
		editTextValorGasto.setText(formatAux.format(
				intent.getExtras().getDouble("valor")).replace(",", "."));

		// adicionando os itens no spinner
		listCategorias = new ArrayList<String>();
		categoriaCursor = categoriaDAO.consultarCategorias();
		for (int i = 0; i < categoriaCursor.getCount(); i++) {
			categoriaCursor.moveToPosition(i);
			listCategorias.add(categoriaCursor.getNomeCategoria());
		}
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, listCategorias);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerCategoria.setAdapter(adapter);
		categoriaDAO.close();
		categoriaCursor.close();

		for (int i = 0; i < spinnerCategoria.getCount(); i++) {
			if (spinnerCategoria.getItemAtPosition(i).toString()
					.equals(intent.getExtras().get("categoria"))) {
				spinnerCategoria.setSelection(i);
			}
		}

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_edicao_gasto, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_editar_gasto:
			Gasto gasto = new Gasto();
			gasto.setIdGasto(idGasto);
			if (editTextNomeGasto.getText().toString().equals("")
					|| editTextNomeGasto.getText().toString().equals("")) {
				gasto.setNomeGasto("Gasto sem t\u00edtulo");
			} else {
				gasto.setNomeGasto(editTextNomeGasto.getText().toString());
			}
			if (editTextValorGasto.getText().toString().equals("")
					|| editTextValorGasto.getText().toString().equals("")) {
				Toast.makeText(this, "Insira um valor.", Toast.LENGTH_SHORT)
						.show();
			} else {
				gasto.setValor(Double.parseDouble(editTextValorGasto.getText()
						.toString()));
				if (spinnerCategoria.getSelectedItemPosition() < 0) {
					Toast.makeText(this, "Selecione uma categoria.",
							Toast.LENGTH_SHORT).show();
					break;
				}
				gasto.setCategoria(spinnerCategoria.getSelectedItem()
						.toString());
				Calendar calendar = Calendar.getInstance();
				gasto.setDataCadastro(formatData.format(calendar.getTime()));

				dao.alterarGasto(gasto);
				Toast.makeText(this, "Gasto alterado.", Toast.LENGTH_SHORT)
						.show();
				startActivity(new Intent(this, PrincipalActivity.class));
				overridePendingTransition(android.R.anim.fade_in,
						android.R.anim.fade_out);
				finish();
				dao.close();
			}
			break;
		default:
			startActivity(new Intent(this, PrincipalActivity.class));
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(this, PrincipalActivity.class));
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
}
